<!--单张图片上传-->
<template>
  <div>
    <div style="display: inline-block;position: relative">
      <div class="upload___file" :style="{width:(width * cropRatio)+'px'}">
        <el-upload
          :show-file-list="false"
          :auto-upload="false"
          :on-change="handleUploadChange"
          :multiple="false"
          accept="image/png,image/jpeg,image/jpg"
          action=""
          :style="{height:(width)+'px'}"
          class="avatar-uploader">
          <img v-if="fileUUID" :src="common.getFileView(fileUUID)" class="avatar" :style="{width:(width * cropRatio - 2)+'px',height:(width)+'px'}">
          <i v-else class="el-icon-plus avatar-uploader-icon" :style="{width:(width * cropRatio)+'px',height:(width)+'px','line-height':(width)+'px'}" />
        </el-upload>
        <div v-if="fileUUID" class="tool-bar">
          <div class="tool-bar-container">
            <el-tooltip class="item" effect="dark" content="文件预览" placement="top">
              <fileViewer :type="1" :url="fileUUID">
                <svg-icon icon-class="btnPreview" />
              </fileViewer>
            </el-tooltip>
            <el-tooltip class="item" effect="dark" content="文件删除" placement="top">
              <svg-icon icon-class="btnRemove" @click="removeFile(fileUUID)" />
            </el-tooltip>
          </div>
        </div>
      </div>
      <div v-if="descShow" class="upload__file_desc">
        <div><i class="el-icon-warning-outline" /> 单张照片不能超过{{ sizeLimit }}M，最多只允许上传1张照片！</div>
        <div v-if="desc"><i class="el-icon-warning-outline" /> {{ desc }}</div>
      </div>
    </div>
    <el-dialog
      title="图片上传"
      :visible.sync="cropperDialogVisible"
      width="500px"
      :before-close="handleClose"
      :modal-append-to-body="false"
      class="upload-file-dialog">
      <el-row :gutter="20">
        <el-col :span="24">支持jpg、jpeg、png，且照片小于{{ sizeLimit }}M。</el-col>
        <el-col :span="15">
          <vue-cropper
            ref="cropper"
            :aspect-ratio="cropRatio"
            :src="cropImgSrc"
            :ready="cropImage"
            :zoom="cropImage"
            :cropmove="cropImage"
            style="width:100%;height:300px;" />
        </el-col>
        <el-col :span="9">
          <h5 style="font-size: 14px;font-weight: bold;">预览：</h5>
          <img :src="cropImgResult" style="width: 120px;border-radius: 5px;">
        </el-col>
      </el-row>
      <span slot="footer" class="dialog-footer">
        <el-button @click="cancelCrop">取 消</el-button>
        <el-button type="primary" plain @click="confirmCropperImage">上传</el-button>
      </span>
    </el-dialog>

  </div>
</template>

<script>
import VueCropper from 'vue-cropperjs'
import 'cropperjs/dist/cropper.css'

export default {
  components: { VueCropper },
  props: {
    value: {
      type: String,
      required: false,
      default() {
        return ''
      }
    },
    catalog: {
      type: String,
      required: true
    },
    width: {
      type: Number,
      required: false,
      default: 128
    },
    sizeLimit: {
      type: Number,
      required: false,
      default: 2
    },
    crop: {
      type: Boolean,
      default: true
    },
    cropRatio: {
      type: Number,
      required: false,
      default: 1 / 1
    },
    desc: {
      type: String,
      required: false,
      default: ''
    },
    descShow: {
      type: Boolean,
      default: true
    }
  },
  data() {
    return {
      fileName: null,
      fileUUID: '',
      uploadSuccessFile: [],
      fileList: [],
      fileStatus: false,
      fileStatusInterval: null,
      cropperDialogVisible: false,
      cropImgSrc: '',
      cropImgResult: ''

    }
  },
  computed: {},
  watch: {
    fileUUID: function(val) {
      if (val) {
        this.$emit('input', val)
      } else {
        this.$emit('input', '')
      }
    },
    value: function(val) {
      console.log(1111, val)
      this.fileUUID = val
    }
  },
  created() {
    this.fileUUID = this.value
  },
  methods: {
    handleClose(done) {
      this.$confirm('确认关闭?').then(_ => {
        done()
      }).catch(_ => {})
    },
    // 选择文件
    handleUploadChange(file) {
      if (!file.raw.type.includes('image/')) {
        this.$modal.msgWarning('请选择图片文件!')
        return
      }
      const isLt = file.size / 1024 / 1024 < this.sizeLimit
      if (!isLt) {
        this.$modal.msgWarning('文件大小不能超过 ' + this.sizeLimit + 'MB!')
        return
      }
      this.fileName = file.name
      if (this.crop) {
        const reader = new FileReader()
        reader.onload = (event) => {
          this.cropperDialogVisible = true
          this.cropImgSrc = event.target.result
          this.$refs.cropper && this.$refs.cropper.replace(event.target.result)
        }
        reader.readAsDataURL(file.raw)
      } else {
        const reader = new FileReader()
        reader.onload = (event) => {
          this.cropImgResult = event.target.result
          this.confirmCropperImage()
        }
        reader.readAsDataURL(file.raw)
      }
    },
    cropImage() {
      this.cropImgResult = this.$refs.cropper.getCroppedCanvas().toDataURL()
    },
    confirmCropperImage() {
      this.fileName = this.fileName.substr(0, this.fileName.lastIndexOf('.'))
      this.$store.dispatch('base64Upload', { base64: this.cropImgResult, catalogId: this.catalog, fileName: this.fileName }).then((res) => {
        this.fileUUID = res.uuid
        this.$modal.msgSuccess('文件上传成功!')
        this.cropperDialogVisible = false
      }).catch((_) => {})
    },
    cancelCrop() {
      this.cropperDialogVisible = false
    },
    async removeFile(uuid) {
      try {
        this.$confirm('此操作将永久删除图片, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.$store.dispatch('fileResourcesRemove', uuid).then(response => {
            this.fileUUID = null
            this.$modal.msgSuccess('删除成功')
          }).catch(() => { this.fileUUID = null })
        }).catch((_) => {

        })
      } catch (_) {
        console.log()
      }
    }
  }
}
</script>
<style rel="stylesheet/scss" lang="scss">
.upload-file-dialog {
  .el-dialog__body {
    padding:0px 20px 20px !important;
  }
  .el-button{
    width: auto;
  }
  .cropper-modal{
    border-radius: 5px !important;
  }
}
</style>
<style rel="stylesheet/scss" lang="scss" scoped>
.upload___file:hover .tool-bar{
  display: block;
}
.upload___file:hover{
  border: 1px dashed #157EFA;
}
.upload___file:hover .avatar-uploader-icon {
  color: #157EFA;
}
.upload___file {
  border: 1px dashed #d9d9d9;
  border-radius: 4px;
  background-color: #F0F7FD;
  cursor: pointer;
  position: relative;
  .tool-bar{
    position: absolute;
    top: 0px;
    height: 2.8em;
    background: rgba(0,0,0,0.8);
    width: 100%;
    border-radius: 4px 4px 0px 0px;
    display: none;
    .tool-bar-container{
      display: flex;
      flex-direction: row;
      justify-content: space-between;
      padding-top: 0.4em;
    }
    .svg-icon{
      width: 1.6em !important;
      height: 1.6em !important;
      color: #fff;
      margin: 0 5px 3px;
    }
  }
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409eff;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    text-align: center;
  }
  .avatar {
    display: block;
    border-radius: 4px;
  }
}
.upload__file_desc{
  color: #A6A6A6;
  font-size: 12px;
  margin-top: 12px;
  i{
    margin-right: 5px;
  }
}
</style>
